package com.dl7.playerdemo;

import com.bumptech.glide.Glide;
import com.dl7.player.danmaku.OnDanmakuListener;
import com.dl7.player.media.IjkPlayerView;
import com.dl7.player.utils.LogUtil;
import com.dl7.player.utils.SoftInputUtils;
import com.dl7.playerdemo.danmaku.DanmakuConverter;
import com.dl7.playerdemo.danmaku.DanmakuData;
import com.dl7.playerdemo.danmaku.DanmakuLoader;
import com.dl7.playerdemo.danmaku.DanmakuParser;
import com.dl7.playerdemo.utils.GsonHelper;
import com.dl7.playerdemo.utils.ScreenUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.global.configuration.Configuration;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.TouchEvent;
import tv.danmaku.ijk.utils.TextUtils;

import java.io.IOException;
import java.io.InputStream;

public class CustomDanmakuActivity extends Ability {

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.DEBUG, 0, "CustomDanmakuActivity");
    private static final String VIDEO_URL = "https://newcntv.qcloudcdn"
            + ".com/asp/hls/450/0303000a/3/default"
            + "/84f142fa588d499d91ef249a01592d95/450.m3u8";
    private static final String IMAGE_URL = "http://vimg2.ws.126.net/image/snapshot/2016/11/I/M/VC62HMUIM.jpg";

    //TODO 未实现
//    Toolbar mToolbar;

    private IjkPlayerView mPlayerView;
    private Component mEtLayout;
    private TextField mEditText;
    private Button mIvSend;
    private Image mImageBack;
    private boolean mIsFocus;
    private DirectionalLayout titleBarLayout;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_activity_custom_danmaku);
        //TODO
//        mToolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(mToolbar);
//        mToolbar.setTitle("Video Player");
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        WindowManager.getInstance().getTopWindow().get().setTransparent(true);
        Window topWindow = WindowManager.getInstance().getTopWindow().get();
        WindowManager.LayoutConfig layoutConfig = new WindowManager.LayoutConfig();
        layoutConfig.title = "Video Player";
        topWindow.setLayoutConfig(layoutConfig);
        titleBarLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_custom_slice_video_titleBar);
        mImageBack = (Image) findComponentById(ResourceTable.Id_custom_image_back);
        mPlayerView = (IjkPlayerView) findComponentById(ResourceTable.Id_custom_player_view);
        mEtLayout = findComponentById(ResourceTable.Id_custom_ll_layout);
        mEditText = (TextField) findComponentById(ResourceTable.Id_custom_et_content);
        mIvSend = (Button) findComponentById(ResourceTable.Id_custom_btn_send);
//        InputStream stream = null;
//        try {
//            stream = getContext().getResourceManager()
//                    .getRawFileEntry("/resources/rawfile/custom.json").openRawFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Glide.with(this).load(IMAGE_URL).fitCenter().into(mPlayerView.mPlayerThumb);

        LogUtil.error("CustomDanmakuActivity", "mUri: " + VIDEO_URL);

        mPlayerView.init()
                .setTitle("这是个跑马灯TextView，标题要足够长才会跑。-(゜ -゜)つロ 乾杯~")
//        屏蔽弹幕功能
                .enableDanmaku()
//                .setDanmakuCustomParser(new AcFunDanmakuParser(), AcFunDanmakuLoader.instance(), null)
//                // 注意 setDanmakuCustomParser() 要在 setDanmakuSource() 前调用
//                .setDanmakuCustomParser(new DanmakuParser(), DanmakuLoader.instance(), DanmakuConverter.instance())
//                .setDanmakuSource(stream)
                .setVideoPath(VIDEO_URL)
//                .setDanmakuListener(new OnDanmakuListener<DanmakuData>() {
//                    @Override
//                    public boolean isValid() {
//                        // TODO: 这里可以控制全屏模式下的是否可以发射弹幕，返回 true 才能发射，可判断用户是否登录
//                        HiLog.warn(LABEL, " 准备发射弹幕");
//                        return true;
//                    }
//
//                    @Override
//                    public void onDataObtain(DanmakuData data) {
//                        // 添加个人信息
//                        data.userName = "LONG";
//                        data.userLevel = 2;
//                        // 这个转换的数据格式 DanmakuData 需要配合 DanmakuConverter 来实现，如果没有设置转换器则默认返回 BaseDanmaku
//                        HiLog.error(LABEL, data.toString());
//                        // GsonHelper.object2JsonStr(data)转换为Json字符串，可以直接保存到文件或服务器，参考{assets/custom.json}文件
//                        HiLog.error(LABEL, GsonHelper.object2JsonStr(data));
//                    }
//                })
        ;
        mPlayerView.initDamukuView("resources/rawfile/comments.xml");


        mImageBack.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminateAbility();
            }
        });

        mIvSend.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                屏蔽弹幕功能
//                mPlayerView.sendDanmaku(mEditText.getText().toString(), false);
                if (TextUtils.isEmpty(mEditText.getText().toString())) {
                    new ToastDialog(CustomDanmakuActivity.this)
                            .setText("内容为空")
                            .show();
                } else {
                    mPlayerView.addDanmaku(mEditText.getText(), true);
                }
                mEditText.setText("");
                _closeSoftInput();
            }
        });

        mEditText.setFocusChangedListener(new Component.FocusChangedListener() {
            @Override
            public void onFocusChange(Component component, boolean isFocus) {
                if (isFocus) {
                    mPlayerView.editVideo();
                }
                mIsFocus = isFocus;
            }
        });
    }

    @Override
    protected void onActive() {
        super.onActive();
        mPlayerView.onResume();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        mPlayerView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPlayerView.onDestroy();
    }

    @Override
    public void onConfigurationUpdated(Configuration configuration) {
        int screenWidth = ScreenUtils.getScreenWidth(this);
        int screenHeight = ScreenUtils.getScreenHeight(this);

        super.onConfigurationUpdated(configuration);

        if (configuration.direction == Configuration.DIRECTION_HORIZONTAL) {
            mPlayerView.setLayoutConfig(new StackLayout.LayoutConfig(screenWidth, screenHeight));
            titleBarLayout.setVisibility(Component.HIDE);
        } else {
            mPlayerView.setLayoutConfig(new StackLayout.LayoutConfig(screenWidth, 600));
            titleBarLayout.setVisibility(Component.VISIBLE);
        }

        mPlayerView.configurationChanged(configuration);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mPlayerView.handleVolumeKey(keyCode)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mPlayerView.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected boolean onTouchEvent(TouchEvent event) {
        Component component = getCurrentFocus();
        if (_isHideSoftInput(component, (int) event.getPointerPosition(event.getIndex()).getX(),
                (int) event.getPointerPosition(event.getIndex()).getY())) {
            _closeSoftInput();
            return true;
        }
        return super.onTouchEvent(event);
    }

    private void _closeSoftInput() {
        SoftInputUtils.closeSoftInput(this);
        mEditText.clearFocus();
        mPlayerView.recoverFromEditVideo();
    }

    private boolean _isHideSoftInput(Component component, int x, int y) {
        if (component == null || !(component instanceof TextField) || !mIsFocus) {
            return false;
        }
        return x < mEtLayout.getLeft()
                || x > mEtLayout.getRight()
                || y < mEtLayout.getTop();
    }

}
